package sale.wxb.loveshopping.config;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.List;
import java.util.TimeZone;

@Configuration
public class JacksonConfig implements WebMvcConfigurer {

    @Value("${spring.jackson.date-format}")
    private String dateFormat;
    @Value("${spring.jackson.time-zone}")
    private String timeZone;

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = converter.getObjectMapper();
        // 处理long类型超过前端最大值序列化方法
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, BigNumberSerializer.INSTANCE);
        simpleModule.addSerializer(Long.TYPE, BigNumberSerializer.INSTANCE);
        // 转换 LocalDateTime 类型 jackson 默认是处理 Date 不会处理新的日期对象 这里自定义序列化器处理
        simpleModule.addSerializer(LocalDateTime.class, LocalDateSerializer.INSTANCE);
        objectMapper.registerModule(simpleModule);
        // 日期格式化
        objectMapper.setDateFormat(new SimpleDateFormat(dateFormat));
        objectMapper.setTimeZone(TimeZone.getTimeZone(timeZone));
        // 设置格式化内容
        converter.setObjectMapper(objectMapper);
        converters.add(0, converter);
    }
}
